<?php

namespace Modules\Order\Entities;

use Illuminate\Database\Eloquent\Builder;
use \Modules\Order\Entities\BaseOrder;

use ThrowException;
use Setting;

class ProductOrder extends BaseOrder
{
    protected $guarded = [];
    protected $table = 'orders';

    static public $resourceName = '标准订单';
    static public $orderType = 'product';

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('normalOrder', function(Builder $builder) {
            $builder->type('product');
        });
    }

    static public function calcCarriage($skuableMaps)
    {
        // $noFreeCarriage = 0; // 不包邮的sku数量
        $carriage = 0;
        $carriageType = 1;  // 1为在线支付邮费  2为到付

        // $sysCarriage = @Setting::get('sys_order')['product_carriage'] ?: 0;

        $noFreeCarriage = 0;
        $temp = 0;

        foreach ($skuableMaps as $skuable) {
            $carriageType = $skuable['skuable']->parent_product->carriage_type;

            // 按统一设置
            if ($carriageType === 0) {
                // $temp = $sysCarriage;
                $noFreeCarriage += $skuable['total'];
            } 
            elseif ($carriageType === 1) {
                $temp = 0;
            }
            elseif ($carriageType === 2) {
                // 到付，全部为到付
                $temp = 0;
                $carriageType;
                break;
            }
            elseif ($carriageType === 3) {
                $temp = $skuable['skuable']->parent_product->carriage;
            }

            if ($temp > $carriage) {
                $carriage = $temp;
            }
        }

        if ($noFreeCarriage > 0) {
            $carriageList = @Setting::get('sys_carriage')['product']  ?: [];  

            for ($i = count($carriageList) - 1;  $i>=0; $i --)
            {
                $total = @$carriageList[$i]['total'] ?: 0;
                if ($noFreeCarriage >= $total) {
                    $carriage = @$carriageList[$i]['carriage'] ?: 0;
                    break;
                }
            } 
        }

        return [
            $carriageType,
            $carriage
        ];
    }
}
